package com.central;

import com.central.scheduler.service.alert.AlertClientService;
import com.central.scheduler.service.bean.SpringApplicationContext;
import com.central.scheduler.common.Constants;
import com.central.scheduler.common.IStoppable;
import com.central.scheduler.common.enums.NodeType;
import com.central.scheduler.common.thread.Stopper;
import com.central.scheduler.remote.NettyRemotingServer;
import com.central.scheduler.remote.command.CommandType;
import com.central.scheduler.remote.config.NettyServerConfig;
import com.central.scheduler.worker.config.WorkerConfig;
import com.central.scheduler.worker.plugin.TaskPluginManager;
import com.central.scheduler.worker.processor.DBTaskAckProcessor;
import com.central.scheduler.worker.processor.DBTaskResponseProcessor;
import com.central.scheduler.worker.processor.TaskExecuteProcessor;
import com.central.scheduler.worker.processor.TaskKillProcessor;
import com.central.scheduler.worker.registry.WorkerRegistryClient;
import com.central.scheduler.worker.runner.RetryReportTaskStatusThread;
import com.central.scheduler.worker.runner.WorkerManagerThread;
import com.central.scheduler.spi.exception.PluginNotFoundException;
import com.central.scheduler.spi.plugin.PluginLoader;
import com.central.scheduler.spi.plugin.PluginManagerConfig;
import com.google.common.collect.ImmutableList;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.FilterType;
import javax.annotation.PostConstruct;

/**
 * @author Tindy
 * @date 2021/10/25
 * @describe
 */
@ComponentScan(value = "com.central.scheduler", excludeFilters = {
        @ComponentScan.Filter(type = FilterType.REGEX, pattern = {
                "com.central.scheduler.service.alert.*",
                "com.central.scheduler.service.process.*",
        })
})
@SpringBootApplication
public class WorkerServerApp implements IStoppable {

    /**
     * logger
     */
    private static final Logger logger = LoggerFactory.getLogger(WorkerServerApp.class);
    /**
     * worker config
     */
    @Autowired
    private WorkerConfig workerConfig;
    /**
     * netty remote server
     */
    private NettyRemotingServer nettyRemotingServer;
    /**
     * spring application context
     * only use it for initialization
     */
    @Autowired
    private SpringApplicationContext springApplicationContext;

    /**
     * alert model netty remote server
     */
    private AlertClientService alertClientService;
    @Autowired
    private RetryReportTaskStatusThread retryReportTaskStatusThread;

    @Autowired
    private WorkerManagerThread workerManagerThread;

    /**
     * worker registry
     */
    @Autowired
    private WorkerRegistryClient workerRegistryClient;

    private TaskPluginManager taskPluginManager;


    /**
     * worker server startup, not use web service
     *
     * @param args arguments
     */
    public static void main(String[] args) {
        Thread.currentThread().setName(Constants.THREAD_NAME_WORKER_SERVER);
        SpringApplication.run(WorkerServerApp.class, args);
    }
    /**
     * worker server run
     */
    @PostConstruct
    public void run() {
        // alert-server client registry
        alertClientService = new AlertClientService(workerConfig.getAlertListenHost(), Constants.ALERT_RPC_PORT);
        // init task plugin
        initTaskPlugin();
        // init remoting server
        NettyServerConfig serverConfig = new NettyServerConfig();
        serverConfig.setListenPort(workerConfig.getListenPort());
        this.nettyRemotingServer = new NettyRemotingServer(serverConfig);
        this.nettyRemotingServer.registerProcessor(CommandType.TASK_EXECUTE_REQUEST, new TaskExecuteProcessor(alertClientService, taskPluginManager));
        this.nettyRemotingServer.registerProcessor(CommandType.TASK_KILL_REQUEST, new TaskKillProcessor());
        this.nettyRemotingServer.registerProcessor(CommandType.DB_TASK_ACK, new DBTaskAckProcessor());
        this.nettyRemotingServer.registerProcessor(CommandType.DB_TASK_RESPONSE, new DBTaskResponseProcessor());
        this.nettyRemotingServer.start();

        // worker registry
        try {
            this.workerRegistryClient.registry();
            this.workerRegistryClient.setRegistryStoppable(this);
            String workerZkPath = this.workerRegistryClient.getWorkerZkPath();

            this.workerRegistryClient.handleDeadServer(workerZkPath, NodeType.WORKER, Constants.DELETE_OP);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }

        // task execute manager
        this.workerManagerThread.start();

        // retry report task status
        this.retryReportTaskStatusThread.start();

        /**
         * registry hooks, which are called before the process exits
         */
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            if (Stopper.isRunning()) {
                close("shutdownHook");
            }
        }));
    }


    private void initTaskPlugin() {
        taskPluginManager = new TaskPluginManager();
        PluginManagerConfig taskPluginManagerConfig = new PluginManagerConfig();
        taskPluginManagerConfig.setPlugins(workerConfig.getTaskPluginBinding());
        if (StringUtils.isNotBlank(workerConfig.getTaskPluginDir())) {
            taskPluginManagerConfig.setInstalledPluginsDir(workerConfig.getTaskPluginDir().trim());
        }

        if (StringUtils.isNotBlank(workerConfig.getMavenLocalRepository())) {
            taskPluginManagerConfig.setMavenLocalRepository(workerConfig.getMavenLocalRepository().trim());
        }

        PluginLoader taskPluginLoader = new PluginLoader(taskPluginManagerConfig, ImmutableList.of(taskPluginManager));
        try {
            taskPluginLoader.loadPlugins();
        } catch (Exception e) {
            throw new RuntimeException("Load Task Plugin Failed !", e);
        }
        if (MapUtils.isEmpty(taskPluginManager.getTaskChannelMap())) {
            throw new PluginNotFoundException("Task Plugin Not Found,Please Check Config File");
        }
    }

    public void close(String cause) {

        try {
            // execute only once
            if (Stopper.isStopped()) {
                return;
            }

            logger.info("worker server is stopping ..., cause : {}", cause);

            // set stop signal is true
            Stopper.stop();

            try {
                // thread sleep 3 seconds for thread quitely stop
                Thread.sleep(3000L);
            } catch (Exception e) {
                logger.warn("thread sleep exception", e);
            }

            // close
            this.nettyRemotingServer.close();
            this.workerRegistryClient.unRegistry();
            this.alertClientService.close();
            this.springApplicationContext.close();
        } catch (Exception e) {
            logger.error("worker server stop exception ", e);
        }
    }
    @Override
    public void stop(String cause) {
        close(cause);
    }
}